package com.gec.system.controller;

import com.gec.system.exception.MyCustomException;
import com.gec.system.service.SysUserService;
import com.gec.system.system.SysUser;
import com.gec.system.util.JwtHelper;
import com.gec.system.util.Result;
import com.gec.system.util.MDHelper;
import com.gec.system.vo.SysLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin/system/index")
@Api(tags = "系统登录")
public class LoginController {
    private static final Logger log = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    SysUserService userService;
    @ApiOperation("登录")
    @PostMapping("/login")
    public Result login(@RequestBody SysLoginVo loginVo){
        SysUser sysUser = userService.getUserInfoUserName(loginVo.getUsername());
        if (sysUser==null){
            throw new MyCustomException(20001,"用户不存在");
        }
        String password = loginVo.getPassword();
        password = MDHelper.encrypt(password);
        if (!sysUser.getPassword().equals(password)){
            throw new MyCustomException(20002,"密码错误");

        }
        if (sysUser.getStatus()==0){
            throw new MyCustomException(20003,"账号被停用..");

        }
        String token = JwtHelper.createToken(sysUser.getId() + "", sysUser.getUsername());
        Map<String,Object> map =new HashMap<>();
        map.put("token",token);
        System.out.println(map);
        return  Result.ok(map);
    }
    @ApiOperation("info方法")
    @GetMapping("/info")
    public Result info(HttpServletRequest request){
        if(request.getHeader("token")==null){
            log.warn(request.getHeader("token"));
            return null;
        }
        String token = request.getHeader("token");

        String username = JwtHelper.getUsername(token);
        Map<String,Object> map =  userService.getUserInfo(username);
        System.out.print(map);
        return Result.ok(map);
    }
    @PostMapping("/logout")
    public Result logout(){
        return Result.ok();
    }
}
